package com.ruoyi.system.billiards.weixin;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.system.billiards.auth.JwtOperator;
import com.ruoyi.system.billiards.domian.response.MemberResp;
import com.ruoyi.system.billiards.service.BilliardsMemberService;
import com.ruoyi.system.billiards.domian.dto.MemberInfo;
import com.ruoyi.system.billiards.domian.request.LoginReq;
import com.ruoyi.system.billiards.domian.response.LoginResp;
import com.ruoyi.system.domain.BilliardsMember;
import lombok.RequiredArgsConstructor;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/wx/billiards/member")
@RequiredArgsConstructor
public class BilliardsMemberController {

    private final BilliardsMemberService billiardsMemberService;

    private final JwtOperator jwtOperator;

    private final WxMaService wxMaService;




    @PutMapping
    public AjaxResult updateMember(@RequestBody BilliardsMember req) {
        if (req.getMemberId() == null) {
            throw new ServiceException("参数错误");
        }
        BilliardsMember member = billiardsMemberService.updateMember(req);
        MemberResp resp = new MemberResp();
        BeanUtils.copyProperties(member, resp);
        return AjaxResult.success(resp);
    }

    @PostMapping("auth")
    public AjaxResult auth(@RequestBody LoginReq req) throws WxErrorException {
        if (StringUtils.isBlank(req.getCode())) {
            throw new ServiceException("参数错误");
        }
        WxMaJscode2SessionResult result = wxMaService.getUserService().getSessionInfo(req.getCode());
        String openid = result.getOpenid();
        BilliardsMember member = billiardsMemberService.login(covert(req, openid));
        // 颁发token
        Map<String, Object> userInfo = new HashMap<>(3);
        userInfo.put("memberId", member.getMemberId());
        userInfo.put("username", member.getUsername());
        String token = jwtOperator.generateToken(userInfo);
        MemberInfo memberInfo = new MemberInfo();
        BeanUtils.copyProperties(member, memberInfo);
        LoginResp loginResp = LoginResp.builder()
                .token(token)
                .expirationTime(jwtOperator.getExpirationTime().getTime())
                .memberInfo(memberInfo)
                .build();
        return AjaxResult.success(loginResp);
    }
    private BilliardsMember covert(LoginReq request, String openid) {
        return BilliardsMember.builder().openid(openid)
                .username(request.getUsername())
                .avatar(request.getAvatar())
                .build();
    }

}
